<!DOCTYPE html>
<html lang="zh-CN">
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<head>
    <meta charset="UTF-8">
    <title>确认订单</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #FFEEF7; /* 浅粉色背景 */
            margin: 0;
            padding: 20px;
            color: #333; /* 文本颜色 */
        }
        .container {
            max-width: 960px;
            margin: 0 auto;
            background: #FFF; /* 容器背景色 */
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        h1 {
            text-align: center;
            color: #333; /* 标题颜色 */
            margin-bottom: 20px;
        }
        button {
            width: 100%;
            padding: 10px;
            background-color: #FF69B4; /* 按钮背景色 */
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px; /* 按钮字体大小 */
            transition: background-color 0.3s ease; /* 过渡效果 */
        }
        button:hover {
            background-color: #FF1493; /* 按钮悬停背景色 */
        }
        .address-item {
            padding: 10px;
            border: 1px solid #ddd;
            margin-bottom: 10px;
            cursor: pointer;
        }
        .address-item:hover {
            background-color: #f9f9f9;
        }
        .address-item.selected {
            background-color: #e9e9e9;
        }
        #message {
            color: #FF0000; /* 错误信息颜色 */
            text-align: center;
            margin-bottom: 20px;
        }
        .order-item {
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>确认订单</h1>
    <div id="message"></div>
    <div id="addressList"></div>
    <button id="checkoutButton">结账</button>
    <div id="cartItems"></div>
</div>

<script>
    let totalAmount = 0; // 全局变量存储总金额
    let subject = ''; // 全局变量存储订单主题
    document.addEventListener('DOMContentLoaded', function() {
        // 获取用户ID
        getUserID().then(userId => {
            if (userId === "not_logged_in") {
                alert('用户未登录');
                return;
            }

            const queryParams = new URLSearchParams(window.location.search);
            const orderId = queryParams.get('orderId');

            if (!orderId) {
                alert('订单ID无效');
                return;
            }

            // 获取订单详情
            fetch(`/api/orders/${orderId}/details`, {
                method: 'GET',
                credentials: 'include'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Failed to fetch order details');
                    }
                    return response.json();
                })
                .then(orderDetails => {
                    displayOrderDetails(orderDetails);
                })
                .catch(error => {
                    console.error('Error fetching order details:', error);
                    document.getElementById('message').innerText = '无法获取订单详情';
                });

            // 获取收货地址列表
            fetchAddresses(userId);
        });
    });

    function displayOrderDetails(orderDetails) {
        const orderDetailsContainer = document.getElementById('cartItems');
        const messageDiv = document.getElementById('message');

        // 清空容器内容
        orderDetailsContainer.innerHTML = '';
        messageDiv.innerHTML = '';

        if (orderDetails.length === 0) {
            messageDiv.textContent = '订单详情为空';
            return;
        }

        // 显示订单信息
        const order = orderDetails[0].order; // 假设只有一个订单
        const currentDate = new Date(); // 获取当前日期
        messageDiv.innerHTML = `
        <p>订单号: ${order.orderID}</p>
        <p>用户ID: ${order.userID}</p>
        <p>状态: ${order.status}</p>
        <p>主题: ${order.subject}</p>
        <p>总金额: $${order.totalAmount}</p>
        <p>订单日期: ${currentDate.toLocaleString()}</p>
    `;

        // 解析订单项
        orderDetails.forEach(detail => {
            const itemElement = document.createElement('div');
            itemElement.className = 'order-item';
            itemElement.innerHTML = `
            <div class="item-image">
                <img src="${detail.product.imageURL}" alt="${detail.product.name}" />
            </div>
            <div class="item-info">
                <h3>${detail.product.name}</h3>
                <p>${detail.product.description}</p>
                <p>数量: ${detail.quantity}</p>
                <p>单价: $${detail.unitPrice}</p>
                <p>小计: $${detail.subtotal}</p>
            </div>
        `;
            orderDetailsContainer.appendChild(itemElement);

            // 更新全局变量
            totalAmount += detail.subtotal; // 累加小计
            subject += `${detail.product.name}, `; // 拼接商品名称
        });

        // 移除最后一个逗号和空格
        subject = subject.slice(0, -2);
    }

    function fetchAddresses(userId) {
        fetch(`/api/users/shipping-addresses/${userId}`, {
            method: 'GET',
            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(addresses => {
                const addressList = document.getElementById('addressList');
                if (addresses.length === 0) {
                    addressList.innerHTML = '<p>没有可用的收货地址。</p>';
                } else {
                    addressList.innerHTML = addresses.map(address => `
                <div class="address-item" data-id="${address.id}">
                    ${address.recipientName}<br>
                    ${address.address}<br>
                    ${address.phone}
                </div>
            `).join('');
                    // 默认选择第一个地址
                    document.querySelectorAll('.address-item')[0].classList.add('selected');
                }
                // 添加点击事件监听器到每个地址项
                document.querySelectorAll('.address-item').forEach(item => {
                    item.addEventListener('click', function() {
                        // 移除其他地址项的选中状态
                        document.querySelectorAll('.address-item').forEach(i => i.classList.remove('selected'));
                        // 为当前点击的地址项添加选中状态
                        this.classList.add('selected');
                    });
                });
            })
            .catch(error => {
                console.error('Error fetching addresses:', error);
                document.getElementById('message').innerText = '无法加载地址信息';
            });
    }

    document.getElementById('checkoutButton').addEventListener('click', function() {
        const selectedAddress = document.querySelector('.address-item.selected');
        if (selectedAddress) {
            const addressId = parseInt(selectedAddress.dataset.id, 10);
            if (isNaN(addressId)) {
                document.getElementById('message').innerText = '请选择一个有效的收货地址';
                return;
            }
            const orderId = new URLSearchParams(window.location.search).get('orderId');
            updateOrderAddress(orderId, addressId);
        } else {
            document.getElementById('message').innerText = '请选择一个收货地址';
        }
    });

    function updateOrderAddress(orderId, addressId) {
        fetch(`/api/orders/update-address?orderid=${Number(orderId)}&addressId=${Number(addressId)}`, {
            method: 'PUT',
            credentials: 'include'
            // 注意：不需要设置Content-Type和请求体
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                document.getElementById('message').innerText = '订单地址更新成功';
                pay(orderId, subject, totalAmount);
            })
            .catch(error => {
                console.error('Error updating order address:', error);
                document.getElementById('message').innerText = '订单地址更新失败';
            });
    }

    function pay(orderId, subject, totalAmount) {
        // 发送请求到后端以获取支付表单
        axios.get(`/api/alipay/pay?subject=${encodeURIComponent(subject)}&traceNo=${orderId}&totalAmount=${totalAmount}`)
            .then(response => {
                // 打开支付宝支付页面
                var payWindow = window.open('', '_blank');
                payWindow.document.write(response.data); // 将返回的表单写入新窗口
                payWindow.document.close(); // 关闭文档以完成加载
            })
            .catch(error => {
                console.error('支付请求失败:', error);
                alert('支付请求失败');
            });
    }

    function getUserID() {
        return fetch('/api/get-user-id', {


            credentials: 'include'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Failed to fetch user ID');
                }
                return response.text();
            })
            .catch(error => {
                console.error('Error fetching user ID:', error);
                alert('无法获取用户ID');
                return Promise.resolve("not_logged_in");
            });
    }
</script>

</body> </html>